//
//  ViewController.m
//  EJPhotoBrowser
//
//  Created by LiuShuang on 2019/6/18.
//  Copyright © 2019 LiuShuang. All rights reserved.
//

#import "ViewController.h"
#import "EJImagePickerNVC.h"
#import "EJVideoPlayerVC.h"
#import "EJAddCell.h"
#import "EJSelectedCell.h"
#import "EJPhotoBrowser.h"
#import "EJCameraShotVC.h"

#import "EJConfigModel.h"

@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, EJImagePickerVCDelegate, EJPhotoBrowserDelegate, EJCameraShotVCDelegate> {
    EJConfigModel * _config;
}

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;

@property (nonatomic, strong) NSMutableArray * dataSource;
@property (nonatomic, strong) NSMutableArray * browserSource;

@property (nonatomic, strong) EJProgressHUD * hud;

@end

@implementation ViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    CGFloat width = floor((self.view.bounds.size.width - 3 * 4) / 3.f);
    self.layout.itemSize = CGSizeMake(width, width);
    self.layout.sectionInset = UIEdgeInsetsMake(3, 3, 3, 3);
    self.layout.minimumLineSpacing = 3;
    self.layout.minimumInteritemSpacing = 3;
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJAddCell" bundle:nil] forCellWithReuseIdentifier:@"EJAddCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSelectedCell" bundle:nil] forCellWithReuseIdentifier:@"EJSelectedCell"];
    
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    _config = [[EJConfigModel alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleConfigDone:) name:@"Config" object:nil];
}

- (IBAction)handleClickUpload:(UIBarButtonItem *)sender {
    BOOL isEnoughFree = [UIDevice isEnoughFreeSizePer:0.1];
    if (!isEnoughFree) {
        UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"手机存储空间不足，\n请先清理空间后再次尝试！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertC addAction:cancelAction];
        [self presentViewController:alertC animated:YES completion:nil];
        return;
    }
}

#pragma mark - action
- (void)handleConfigDone:(NSNotification *)notification {
    NSDictionary * userInfo = notification.userInfo;
    _config = userInfo[@"Config"];
    [self.dataSource removeAllObjects];
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.dataSource count] < 9 ? self.dataSource.count + 1 : self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.dataSource count] < 9 && indexPath.row == self.dataSource.count) {
        EJAddCell * addCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJAddCell" forIndexPath:indexPath];
        return addCell;
    }
    EJSelectedCell * selectedCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSelectedCell" forIndexPath:indexPath];
    NSObject * obj = [self.dataSource objectAtIndex:indexPath.row];
    
    if ([obj isKindOfClass:[EJAssetModifyModel class]]) {
        EJAssetModifyModel * modify = (EJAssetModifyModel *)obj;
        if (modify.image) {
            selectedCell.coverImage.image = modify.image;
        } else {
            PHImageRequestOptions * options = [[PHImageRequestOptions alloc] init];
            options.networkAccessAllowed = YES;
            [[PHImageManager defaultManager] requestImageDataForAsset:modify.asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                selectedCell.coverImage.image = [UIImage imageWithData:imageData];
            }];
        }
    }
    [selectedCell configClickDeleteBlock:^{
        [self.dataSource removeObjectAtIndex:indexPath.row];
        [self.collectionView reloadData];
    }];
    return selectedCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell * cell = [collectionView cellForItemAtIndexPath:indexPath];
    if ([cell isKindOfClass:[EJAddCell class]]) {
        UIAlertController * alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction * shotAction = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self jumpTpShot];
            
        }];
        UIAlertAction * localAction = [UIAlertAction actionWithTitle:@"从本地选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self jumpToSelectLocalImage];
            
            
        }];
        [alertC addAction:shotAction];
        [alertC addAction:localAction];
        [alertC addAction:cancelAction];
        [self presentViewController:alertC animated:YES completion:nil];
        return;
    }
    // 照片浏览
    if ([cell isKindOfClass:[EJSelectedCell class]]) {
//        UIScreen *screen = [UIScreen mainScreen];
//        CGFloat scale = screen.scale;
//        CGFloat imageSize = MAX(screen.bounds.size.width, screen.bounds.size.height) * 1.5;
//        CGSize imageTargetSize = CGSizeMake(imageSize * scale, imageSize * scale);
        self.browserSource = [NSMutableArray arrayWithCapacity:1];
        for (EJAssetModifyModel * modify in self.dataSource) {
//            if ([obj isKindOfClass:[PHAsset class]]) {
//                PHAsset * asset = (PHAsset *)obj;
//                EJPhoto * photo = [EJPhoto photoWithAsset:asset targetSize:imageTargetSize];
//                [self.browserSource addObject:photo];
//            }
//            if ([obj isKindOfClass:[EJAssetModifyModel class]]) {
//                EJAssetModifyModel * modify = (EJAssetModifyModel *)obj;
                if (modify.image) {
                    EJPhoto * photo = [EJPhoto photoWithImage:modify.image];
                    photo.modifyId = modify.asset.localIdentifier;
                    [self.browserSource addObject:photo];
                } else {
                    EJPhoto * photo = [EJPhoto photoWithAsset:modify.asset];
                    [self.browserSource addObject:photo];
                }
//            }
        }
        EJPhotoBrowser * browser = [[EJPhotoBrowser alloc] initWithDelegate:self];
        browser.maxVideoDuration = _config.videoDefaultDuration;
        browser.showSelectButton = YES;
        browser.showCropButton = _config.allowCrop;
        browser.forcedCrop = _config.forcedCrop;
        [browser setCurrentPhotoIndex:indexPath.row];
        browser.isPreview = YES;
        [self.navigationController pushViewController:browser animated:YES];
        return;
    }
}

#pragma mark - jump select local
- (void)jumpToSelectLocalImage {
    // 使用 config 配置
    [self jumpWithConfig];
    
    // 选择用户头像
//    [self jumpToSelectUserHeader];
    
    // 选择 作品集封面
//    [self jumpToSelectWorkbookCover];
    
    // 选择 幼儿园背景
//    [self jumpToSelectSchoolBG];
    
    // 选择 幼儿园logo
//    [self jumpToSelectSchoolLogo];
    
    // 跳转到 富文本编辑器 选择图片
//    [self jumpToSelectRichTextImage];
    
    // 选择幼儿头像
//    [self jumpToSelectStudentHeader];
    
    // 选择 教研档案 封皮
//    [self jumpToSelectFolderCover];
    
    // 选择 图文段落 图片
//    [self jumpToSelectBlogSectionImage];
    
    // 选择成长纪念册的图片
//    [self jumpToSelectYearbook];
    
    // 选择 单个视频
//    [self jumpToSelectSingleVideo];
    
    // 选择 单个视频 create point
//    [self jumpToSelectPointVideo];
    
    // 选择 多个视频
//    [self jumpToSelectMutiVideo];
    
    // 混合选择 一个资源
//    [self jumpToSelectSingleAsset];
    
    //
//    [self jumpToSelectYearbookAsset];
    
//    [self jumpToSelectNotifyAsset];
    
//    [self jumpToSelectBlogAsset];

}

- (void)jumpToSelectBlogAsset {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_All MaxCount:0 SelectedSource:nil orderType:E_OrderSystemNormal showShot:NO allowCrop:YES];
    pickerVC.limitVideoDuration = NO;
    pickerVC.browserAfterShot = NO;
    pickerVC.directEdit = NO;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectNotifyAsset {
    EJImagePickerNVC * vc = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_All MaxCount:50 SelectedSource:self.dataSource orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    vc.limitVideoDuration = NO;
    vc.pickerDelegate = self;
    [self ej_presentViewController:vc animated:YES completion:nil];
}

- (void)jumpToSelectYearbookAsset {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_All MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.limitVideoDuration = NO;
    pickerVC.browserAfterShot = NO;
    pickerVC.directEdit = NO;
    pickerVC.cropScale = 1.5;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectSingleAsset {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_All MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.limitVideoDuration = NO;
    pickerVC.directEdit = NO;
    pickerVC.cropScale = 3 / 4.0;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectMutiVideo {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Video MaxCount:0 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.limitVideoDuration = NO;
    pickerVC.browserAfterShot = NO;
    pickerVC.directEdit = NO;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectPointVideo {
    EJImagePickerNVC * picker = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Video MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:NO allowCrop:YES];
    picker.limitVideoDuration = NO;
    picker.directEdit = NO;
    picker.pickerDelegate = self;
    [self ej_presentViewController:picker animated:YES completion:nil];
}

- (void)jumpToSelectSingleVideo {
    EJImagePickerNVC * vc = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Video MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    vc.limitVideoDuration = NO;
    vc.browserAfterShot = NO;
    vc.directEdit = NO;
    vc.pickerDelegate = self;
    [self ej_presentViewController:vc animated:YES completion:nil];
}

- (void)jumpToSelectYearbook {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.browserAfterShot = NO;
    pickerVC.directEdit = NO;
    pickerVC.cropScale = 1.5;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectBlogSectionImage {
    
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:0 SelectedSource:self.dataSource orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.browserAfterShot = NO;
    pickerVC.directEdit = NO;
    pickerVC.pickerDelegate = self;
    pickerVC.forcedCrop = NO;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectFolderCover {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:NO allowCrop:YES];
    pickerVC.cropScale = 1;
    pickerVC.directEdit = NO;
    pickerVC.forcedCrop = YES;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectStudentHeader {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.directEdit = NO;
    pickerVC.cropScale = 1;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectRichTextImage {
    EJImagePickerNVC * picker = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    picker.browserAfterShot = NO;
    picker.directEdit = NO;
    picker.pickerDelegate = self;
    [self ej_presentViewController:picker animated:YES completion:nil];
}

- (void)jumpToSelectSchoolLogo {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.customTitle = @"更改Logo";
    pickerVC.cropScale = 1;
    pickerVC.browserAfterShot = NO;
    pickerVC.directEdit = NO;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectSchoolBG {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:NO];
    pickerVC.customTitle = @"更改背景";
    pickerVC.browserAfterShot = NO;
    pickerVC.directEdit = NO;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectWorkbookCover {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.directEdit = NO;
    pickerVC.cropScale = 1;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpToSelectUserHeader {
    EJImagePickerNVC * pickerVC = [[EJImagePickerNVC alloc] initWithSourceType:E_SourceType_Image MaxCount:1 SelectedSource:nil orderType:E_OrderSystemNormal showShot:YES allowCrop:YES];
    pickerVC.directEdit = YES;
    pickerVC.cropScale = 1;
    pickerVC.autoPopAfterCrop = NO;
    pickerVC.pickerDelegate = self;
    [self ej_presentViewController:pickerVC animated:YES completion:nil];
}

- (void)jumpWithConfig {
    // 跳转到 本地照片选择
    E_SourceType sourceType = (E_SourceType)_config.sourceType;
    if (_config.maxSelectCount == 1) {
        [self.dataSource removeAllObjects];
    }
    EJImagePickerNVC * vc = [[EJImagePickerNVC alloc] initWithSourceType:sourceType MaxCount:_config.maxSelectCount SelectedSource:self.dataSource orderType:E_OrderSystemNormal showShot:_config.allowShot allowCrop:_config.allowCrop];
    vc.customTitle = @"hhhhh";
    if (_config.allowCrop) {
        vc.directEdit = _config.directEdit;
        vc.cropScale = _config.cropScale;
        vc.maxVideoDuration = _config.videoDefaultDuration;
        //                vc.limitVideoDuration = NO;
    }
    vc.previewDelete = _config.previewDelete;
    vc.forcedCrop = _config.forcedCrop;
    vc.autoPopAfterCrop = NO;
    vc.customCropBorder = [UIImage imageNamed:@"mengceng"];
    vc.customLayerImage = [UIImage imageNamed:@"youxiang"];
    vc.cropWarningTitle = @"请将头像缩放到合适的位置";
    // ui
    [vc configSectionInserts:_config.sectionInsets cellSpace:_config.cellSpace numOfLineCells:_config.numOfLineCells];
    
    // delegate
    vc.pickerDelegate = self;
    [self ej_presentViewController:vc animated:YES completion:nil];
}

#pragma mark - shot type
- (void)jumpTpShot {
    // 使用config 配置选项
    [self jumpToShotByConfig];
    
    // 拍摄 用户头像
//    [self jumpToShotUserHeader];
    
    
//    [self jumpToShotIMImage];
    
//    [self jumpTOShotRecord];
    
//    [self jumpToShotFolderCover];
    
//    [self jumpToShotPointAsset];
    
//    EJCameraShotVC * vc = [[EJCameraShotVC alloc] initWithShotTime:60 shotType:EJ_ShotType_Both delegate:self suggestOrientation:E_VideoOrientationAll maxCount:1];
//    vc.cropScale = 1.5;
//    vc.forcedCrop = NO;
//    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
//    [self ej_presentViewController:nav animated:YES completion:nil];
    
}

- (void)jumpToShotPointAsset {
    EJCameraShotVC * vc = [[EJCameraShotVC alloc] initWithShotTime:60 shotType:EJ_ShotType_Both delegate:self suggestOrientation:E_VideoOrientationAll maxCount:9];
//    if (shotType == EJ_ShotType_Both) {
        vc.allowBoth = NO;
        vc.videoShotCount = 1;
//    }
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self ej_presentViewController:nav animated:YES completion:nil];
}

- (void)jumpToShotFolderCover {
    EJCameraShotVC * shotVC = [[EJCameraShotVC alloc] initWithShotTime:60 shotType:EJ_ShotType_Photo delegate:self suggestOrientation:E_VideoOrientationAll maxCount:1];
    shotVC.cropScale = 1;
    shotVC.forcedCrop = YES;
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:shotVC];
    [self ej_presentViewController:nav animated:YES completion:nil];
}

- (void)jumpTOShotRecord {
    EJCameraShotVC * vc = [[EJCameraShotVC alloc] initWithShotTime:60 shotType:EJ_ShotType_Both delegate:self suggestOrientation:E_VideoOrientationPortrait maxCount:50];
    vc.allowBoth = YES;
    vc.videoShotCount = 1;
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self ej_presentViewController:nav animated:YES completion:nil];
}

- (void)jumpToShotIMImage {
    EJCameraShotVC * vc = [[EJCameraShotVC alloc] initWithShotTime:10 shotType:EJ_ShotType_Photo delegate:self suggestOrientation:E_VideoOrientationAll maxCount:1];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self ej_presentViewController:nav animated:YES completion:nil];
}

- (void)jumpToShotUserHeader {
    EJCameraShotVC * vc = [[EJCameraShotVC alloc] initWithShotTime:1 shotType:EJ_ShotType_Photo delegate:self suggestOrientation:E_VideoOrientationPortrait maxCount:1];
    vc.forcedCrop = YES;
    vc.directCrop = YES;
    vc.cropScale = 1;
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self ej_presentViewController:nav animated:YES completion:nil];
}

- (void)jumpToShotByConfig {
    EJ_ShotType shotType = EJ_ShotType_Both;
    if (_config.sourceType == E_SourceType_Image) {
        shotType = EJ_ShotType_Photo;
    }
    if (_config.sourceType == E_SourceType_Video) {
        shotType = EJ_ShotType_Video;
    }
    NSUInteger maxCount = (_config.maxSelectCount == 0 ? NSUIntegerMax : _config.maxSelectCount);
    EJCameraShotVC * vc = [[EJCameraShotVC alloc] initWithShotTime:_config.videoDefaultDuration shotType:shotType delegate:self suggestOrientation:E_VideoOrientationPortrait maxCount:maxCount];
    vc.forcedCrop = _config.forcedCrop;
    vc.cropScale = _config.cropScale;
    vc.allowBoth = NO;
    vc.videoShotCount = 1;
    vc.directCrop = YES;
    vc.customCropBorder = [UIImage imageNamed:@"mengceng"];
    vc.customLayerImage = [UIImage imageNamed:@"youxiang"];
    vc.cropWarningTitle = @"请将头像缩放到合适的位置";
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self ej_presentViewController:nav animated:YES completion:nil];
}

#pragma mark - EJPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(EJPhotoBrowser *)photoBrowser {
    return [self.browserSource count];
}

- (id<EJPhoto>)photoBrowser:(EJPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    return [self.browserSource objectAtIndex:index];
}

- (BOOL)photoBrowser:(EJPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
    EJPhoto * photo = [self.browserSource objectAtIndex:index];
    PHAsset * indexAsset = photo.asset;
    if (indexAsset == nil && [photo.modifyId length] == 0) {
        return NO;
    }
    
    NSString * assetId;
    if (indexAsset) {
        assetId = indexAsset.localIdentifier;
    } else if ([photo.modifyId length] > 0) {
        assetId = photo.modifyId;
    }
    
    for (EJAssetModifyModel * item in self.dataSource) {
        if ([item.asset.localIdentifier isEqualToString:assetId]) {
            return YES;
        }
    }
    return NO;
}

- (void)photoBrowser:(EJPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
    EJPhoto * photo = [self.browserSource objectAtIndex:index];
    PHAsset * indexAsset = photo.asset;
    if (photo.isVideo && indexAsset == nil) {
        return;
    }
    if (photo.isVideo == NO && indexAsset == nil && photo.image == nil) {
        return;
    }
    
    if (selected) {
        if (indexAsset) {
            EJAssetModifyModel * modify = [[EJAssetModifyModel alloc] init];
            modify.asset = indexAsset;
            [self.dataSource addObject:modify];
        } else if ([photo.modifyId length] > 0) {
            PHAsset * asset = [[PHAsset fetchAssetsWithLocalIdentifiers:@[photo.modifyId] options:nil] lastObject];
            EJAssetModifyModel * modify = [[EJAssetModifyModel alloc] init];
            modify.asset = asset;
            modify.image = photo.image;
            [self.dataSource addObject:modify];
        }
    } else {
        
        NSString * assetId;
        if (indexAsset) {
            assetId = indexAsset.localIdentifier;
        } else if (photo.image) {
            assetId = photo.modifyId;
        }
        if ([assetId length] == 0) {
            return;
        }
        
        for (EJAssetModifyModel * item in self.dataSource.reverseObjectEnumerator) {
            if ([item.asset.localIdentifier isEqualToString:assetId]) {
                [self.dataSource removeObject:item];
                break;
            }
        }
        if (photoBrowser.isPreview && _config.previewDelete) {
            [self.browserSource removeObject:photo];
            [photoBrowser reloadData];
        }
    }
}

- (BOOL)photoBrowserCanPhotoSelectedAtIndex:(EJPhotoBrowser *)photoBrowser {
    return YES;
}

- (void)photoBrowserDidFinish:(EJPhotoBrowser *)photoBrowser {
    [self.collectionView reloadData];
}

- (void)photoBrowserDidCancel:(EJPhotoBrowser *)photoBrowser {
    [self.collectionView reloadData];
}

- (NSUInteger)photoBrowserSelectedPhotoCount:(EJPhotoBrowser *)photoBrowser {
    return self.dataSource.count;
}

- (NSUInteger)photoBrowserMaxSelectePhotoCount:(EJPhotoBrowser *)photoBrowser {
    return _config.maxSelectCount;
}

- (CGFloat)photoBrowser:(EJPhotoBrowser *)photoBrowser crapScaleAtIndex:(NSUInteger)index {
    return _config.cropScale;
}

- (void)photoBrowser:(EJPhotoBrowser *)photoBrowser didCropVideoAtIndex:(NSUInteger)index assetId:(NSString *)assetId {
    EJPhoto * photo = [self.browserSource objectAtIndex:index];
    PHAsset * indexAsset = photo.asset;
    if (indexAsset == nil) {
        [photoBrowser reloadData];
        return;
    }
    
    PHAsset * currentAsset;
    for (EJAssetModifyModel * item in self.dataSource) {
//        if ([item isKindOfClass:[PHAsset class]]) {
        PHAsset * itemAsset = item.asset;
        if ([itemAsset.localIdentifier isEqualToString:indexAsset.localIdentifier]) {
            currentAsset = itemAsset;
            break;
        }
//        }
    }
    PHAsset * asset = [[PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil] firstObject];
//    UIScreen *screen = [UIScreen mainScreen];
//    CGFloat scale = screen.scale;
//    CGFloat imageSize = MAX(screen.bounds.size.width, screen.bounds.size.height) * 1.5;
//    CGSize imageTargetSize = CGSizeMake(imageSize * scale, imageSize * scale);
    EJPhoto * currPhoto = [EJPhoto photoWithAsset:asset];
    EJAssetModifyModel * modify = [[EJAssetModifyModel alloc] init];
    modify.asset = asset;
    if (currentAsset) {
        NSUInteger currentIndex = [self.dataSource indexOfObject:currentAsset];
        [self.dataSource replaceObjectAtIndex:currentIndex withObject:modify];
        if (photoBrowser.isPreview) {
            [self.browserSource replaceObjectAtIndex:currentIndex withObject:currPhoto];
        } else {
            [self.browserSource insertObject:currPhoto atIndex:0];
        }
    } else {
        [self.dataSource addObject:modify];
        [self.browserSource insertObject:currPhoto atIndex:0];
    }
    [photoBrowser reloadData];
}

- (void)photoBrowser:(EJPhotoBrowser *)photoBrowser didCropImageAtIndex:(NSUInteger)index image:(UIImage *)resultImage {
    EJPhoto * photo = [self.browserSource objectAtIndex:index];
    PHAsset * indexAsset = photo.asset;
    if (indexAsset == nil && photo.image == nil) {
        [photoBrowser reloadData];
        return;
    }
    
    NSString * assetId;
    if (indexAsset) {
        assetId = indexAsset.localIdentifier;
    } else {
        assetId = photo.modifyId;
    }
    if ([assetId length] == 0) {
        return;
    }
    
    NSObject * currentObj;
    for (EJAssetModifyModel * modify in self.dataSource) {
        if ([modify.asset.localIdentifier isEqualToString:assetId]) {
            modify.image = resultImage;
            currentObj = modify;
            break;
        }
    }
    
    EJPhoto * currentPhoto = [EJPhoto photoWithImage:resultImage];
    currentPhoto.modifyId = assetId;
    if (currentObj) {
        if ([currentObj isKindOfClass:[PHAsset class]]) {
            PHAsset * asset = (PHAsset *)currentObj;
            EJAssetModifyModel * modify = [[EJAssetModifyModel alloc] init];
            modify.asset = asset;
            modify.image = resultImage;
            [self.dataSource replaceObjectAtIndex:index withObject:modify];
        }
        if (photoBrowser.isPreview) {
            [self.browserSource replaceObjectAtIndex:index withObject:currentPhoto];
        } else {
            [self.browserSource insertObject:currentPhoto atIndex:0];
        }
    } else {
        EJAssetModifyModel * modify = [[EJAssetModifyModel alloc] init];
        modify.asset = indexAsset;
        modify.image = resultImage;
        [self.dataSource addObject:modify];
        [self.browserSource insertObject:currentObj atIndex:0];
    }
    [photoBrowser reloadData];
}

#pragma mark - EJCameraShotVCDelegate
- (void)ej_shotVCDidShot:(NSArray<EJAssetModifyModel *> *)assets {
//    PHFetchResult * result = [PHAsset fetchAssetsWithLocalIdentifiers:assets options:nil];
    [self.dataSource removeAllObjects];
//    [result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        [self.dataSource addObject:obj];
//    }];
    
    [self.dataSource addObjectsFromArray:assets];
    [self.collectionView reloadData];
}

- (void)ej_shotVC:(EJCameraShotVC *)shotVC didCropped:(EJAssetModifyModel *)modify {
    UIWindow * window = [UIApplication sharedApplication].delegate.window;
    _hud = [EJProgressHUD ej_showHUDAddToView:window animated:YES];
    _hud.label.text = @"头像上传中...";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_hud hideAnimated:YES];
        [shotVC dismissViewControllerAnimated:YES completion:nil];
    });
}

#pragma mark - EJImagePickerVCDelegate
- (void)ej_imagePickerVC:(EJImagePickerNVC *)imagePicker didSelectedSource:(NSMutableArray <EJAssetModifyModel *>*)source {
    self.dataSource = source;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];
    });
}

- (void)ej_imagePickerVC:(EJImagePickerNVC *)imagePicker didCroppedImage:(UIImage *)image {
    UIWindow * window = [UIApplication sharedApplication].delegate.window;
    _hud = [EJProgressHUD ej_showHUDAddToView:window animated:YES];
    _hud.label.text = @"头像上传中...";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_hud hideAnimated:YES];
        if (imagePicker.isAutoPopAfterCrop) {
            //
        } else {
            [imagePicker dismissViewControllerAnimated:NO completion:^{
                [imagePicker dismissViewControllerAnimated:YES completion:nil];
            }];
        }
    });
}

#pragma mark - getter or setter
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataSource;
}
    
@end
